/**
  * axios http
  * created by yureturn on 17/9/20
  */
import axios from 'axios';

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.validateStatus = (status) => status >= 200 && status < 500;
// axios.defaults.transformRequest = [function (data) {
//   const ret = [];
//   for (const it in data) {
//     ret.push(`${encodeURIComponent(it)}=${encodeURIComponent(data[it])}`);
//   }
//   return ret.join('&');
// }];

// http response 拦截器
axios.interceptors.response.use(response => {
  // @ts-expect-error
  const { status, headers, data } = response;
  // @ts-expect-error
  const { code } = data || {}; 
  // @ts-expect-error
  const { sessionstatus } = headers;
  // 如果返回 sessionstatus 是 timeout 则说明 ssoid 过期
  // 重定向到登录页 code是-201，也需要跳转到登录页面
//   if (code === -201 || sessionstatus === 'timeout') {
//     if (location.host.indexOf('localhost') > -1) {
//       alert('请先在test环境登录');
//       return;
//     }
//     // 跳转到未登录页面
//     if (location.pathname !== '/admin/welcome')
//       window.location.href = `/admin/welcome?beforeLoginUri=${encodeURIComponent(
//         location.href
//       )}`;
//     return Promise.reject('请重新登陆');
//   } else if (code === -202 || sessionstatus === 'unauthorized') {
//     if (location.host.indexOf('localhost') > -1) {
//       alert('请先在烽火台 test环境登录!');
//       return;
//     }
//     // 跳转到无权限页面
//     if (location.pathname !== '/admin/forbidden') {
//       window.location.href = '/admin/forbidden';
//     }
//     return Promise.reject('没有权限');
//   } else if (code === -203) {
//     // // 跳转到反爬虫页面
//     // window.location.href = `/admin/mtsi?url=${encodeURIComponent(
//     //   request.responseURL
//     // )}`;
//   }
//   // 多设备登录被踢下线
//   if (sessionstatus === 'logininvalid' && location.href.indexOf('loginAbnormal') < 0) {
//     // @ts-expect-error
//     window.location.href = `/admin/login/abnormal?bmUserId=${window.userInfo.bmUserId}`;
//   }

  return data;
}, error => Promise.reject(error));

// get请求
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rawRequestGet = (url: string, params: any) => axios({
  url,
  method: "get",
  params
});
// query提交
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rawRequestPostAsQuery = (url: string, params: any) => axios({
  url,
  method: "post",
  params
});

// json提交
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rawRequestPostAsJson = (url: string, data: any) => axios({
  url,
  method: "post",
  headers: {
    'Content-Type': 'application/json'
  },
  data
});

// 表单提交
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rawRequestPostAsForm = (url: string, data: any) => axios({
  url,
  method: "post",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: new URLSearchParams(data).
    toString()
});


const http = {
  rawRequestGet,
  rawRequestPostAsQuery,
  rawRequestPostAsJson,
  rawRequestPostAsForm
};


export default http;